package com.server.controller;

import com.server.common.Result;
import com.server.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Map;
import java.util.Random;


@CrossOrigin
@RestController
@RequestMapping("/mail")
public class MailController {

	@Autowired
	private MailService mailService;

	@Autowired
	private StringRedisTemplate redisTemplate;
	/**
	 * 发送简单邮件
	 */
	@PostMapping("/sendCaptcha")
	public Result sendCaptcha(@RequestBody Map<String, String> map)  {
		String to = map.get("to");
		String subject="验证码";
		Random random = new Random();
		StringBuilder captcha = new StringBuilder();
		for (int i = 0; i < 6; i++) {
			int digit = random.nextInt(10);  // 每次生成 0 到 9 的随机数
			captcha.append(digit);
		}
		redisTemplate.opsForValue().set(to, captcha.toString(), Duration.ofMinutes(5));  // 存储验证码并设置过期时间
		String body = "您的验证码是:"+captcha.toString()+",5分钟内有效。";

		mailService.sendSimpleMail(to, subject, body);
		return Result.suc(null,1L);
	}

}